<!-- src/views/AdminManage.vue -->
<template>
    <div class="admin-manage-page">
        <div class="table-title">管理员成员管理</div>
        <div class="admin-form-container">
            <van-form @submit="onSubmit">
                <van-cell-group inset>
                    <van-field v-model="adminForm.username" name="username" label="用户名" placeholder="请输入用户名"
                        :rules="[{ required: true, message: '请填写用户名' }]" />
                    <van-field v-model="adminForm.password" type="password" name="password" label="密码"
                        placeholder="请输入密码" :rules="[{ required: true, message: '请填写密码' }]" />
                    <van-field v-model="adminForm.confirmPassword" type="password" name="confirmPassword" label="确认密码"
                        placeholder="请再次输入密码" :rules="[
                            { required: true, message: '请确认密码' },
                            {
                                validator: confirmPasswordValidator,
                                message: '两次输入的密码不一致'
                            }
                        ]" />
                </van-cell-group>

                <div class="submit-button">
                    <van-button round block type="primary" native-type="submit">
                        添加管理员
                    </van-button>
                </div>
            </van-form>
        </div>

        <!-- 管理员列表 -->
        <div class="admin-list-container">
            <div class="section-title">现有管理员</div>
            <van-list finished-text="没有更多了">
                <van-cell v-for="admin in adminList" :key="admin.id" :title="admin.username"
                    :label="`密码:${admin.mobile}`" is-link>
                    <template #right-icon>
                        <div class="button-group">
                            <van-button size="small" type="primary" plain @click.stop="editAdmin(admin)">编辑</van-button>
                            <van-button size="small" type="danger" plain
                                @click.stop="deleteAdmin(admin.id)">删除</van-button>
                        </div>
                    </template>
                </van-cell>
            </van-list>
        </div>
    </div>
    <!-- 编辑管理员弹窗 -->
    <van-dialog v-model:show="showEditDialog" title="编辑管理员" show-cancel-button @confirm="saveEditAdmin">
        <van-form ref="editFormRef" @submit="saveEditAdmin">
            <van-cell-group inset>
                <van-field v-model="editForm.username" name="username" label="用户名" placeholder="请输入用户名"
                    :rules="[{ required: true, message: '请填写用户名' }]" />
                <van-field v-model="editForm.password" type="password" name="password" label="新密码"
                    placeholder="不修改请留空" />
            </van-cell-group>
        </van-form>
    </van-dialog>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { showSuccessToast, showFailToast, showConfirmDialog } from 'vant'
import { addUser, deleteUser, getUserList, updateUser } from '../api/user'
interface AdminForm {
    username: string
    password: string
    confirmPassword: string
}

interface AdminInfo {
    id: number
    username: string
    mobile?: string // 添加可选字段 mobile
    password?: string
}
const adminForm = ref<AdminForm>({
    username: '',
    password: '',
    confirmPassword: ''
})
const adminList = ref<AdminInfo[]>([])
// 控制编辑弹窗显示状态
const showEditDialog = ref(false)

// 编辑表单引用
const editFormRef = ref()



// 确认密码验证器
const confirmPasswordValidator = (val: string) => {
    return val === adminForm.value.password
}

// 提交表单
const onSubmit = async (values: AdminForm) => {
    // 这里应该调用API保存管理员信息
    console.log('提交管理员信息:', values)
    await addAdmin()

}
// 编辑表单数据
const editForm = ref<AdminForm>({
    username: '',
    password: '',
    confirmPassword: ''
})

// 当前编辑的管理员ID
const currentEditId = ref<number | null>(null)
// 根据ID查找管理员
const findAdminById = () => {
    if (currentEditId.value !== null) {
        const admin = adminList.value.find(admin => admin.id === currentEditId.value)
        return admin
    }
    return null
}

// 修改删除管理员方法（添加确认提示）
const deleteAdmin = (id: number) => {
    showConfirmDialog({
        title: '确认删除',
        message: '确定要删除这个管理员吗？',
    }).then(async () => {
        // 执行删除操作
        console.log('删除管理员ID:', id)
        await deleteUser(id)
        showSuccessToast('删除成功')
        loadAdminList()
    }).catch(() => {
        // 取消删除
    })
}
// 加载管理员列表
const loadAdminList = async () => {
    // 模拟数据，实际应该从API获取
    adminList.value = [
        { id: 1, username: 'admin' },
        { id: 2, username: 'manager' }
    ]
    const response: any = await getUserList()
    if (response.code === 200) {
        // 过滤出role为"管理员"的数据
        adminList.value = response.data.filter((item: any) => item.role === '管理员')

    }
    else {
        // 失败时使用模拟数据
        adminList.value = [
            { id: 1, username: 'admin' },
            { id: 2, username: 'manager' }
        ]
        showFailToast('加载管理员列表失败')
    }
}
// 编辑管理员
const editAdmin = (admin: AdminInfo) => {
    currentEditId.value = admin.id
    editForm.value = {
        username: admin.username,
        password: '',
        confirmPassword: ''
    }
    showEditDialog.value = true
}
// 保存编辑的管理员信息
const saveEditAdmin = async () => {
    // 这里应该调用API保存管理员信息
    const updateData = findAdminById()
    if (!updateData) {
        showFailToast('未找到该管理员')
        return
    }
    updateData.username = editForm.value.username
    // 只有密码不为空时才更新数据
    if (editForm.value.password) {
        updateData.password = editForm.value.password
        updateData.mobile = editForm.value.password
        console.log("更新数据", updateData)
    }
    await updateUser(updateData)
    showSuccessToast('管理员信息更新成功')
    showEditDialog.value = false
    loadAdminList() // 刷新列表
}
//新增管理员用户方法
const addAdmin = async () => {
    const params = {
        "id": Math.floor(Math.random() * 1000000),
        "username": adminForm.value.username,
        "password": adminForm.value.password,
        "mobile": adminForm.value.password,
        "status": 1,  // 默认启用状态
        "version": 0,
        "createdAt": "",
        "updatedAt": "",
        "enterpriseId": 0,
        "role": "管理员"
    }
    const response: any = await addUser(params)
    if (response.code === 200) {
        showSuccessToast('添加成功')
        adminForm.value = {
            username: '',
            password: '',
            confirmPassword: ''
        }
        loadAdminList()
    } else {
        showFailToast(response.message)
    }

}

onMounted(async () => {
    // 加载管理员列表
    await loadAdminList()

})


</script>

<style scoped>
.admin-manage-page {
    min-height: 100vh;
    width: 100vw;
    background-color: #f5f5f5;
}

.admin-form-container {
    margin: 15px;
    background: white;
    border-radius: 10px;
    padding: 10px 0;
}

.table-title {
    text-align: center;
    font-weight: bold;
    background-color: #e0e0e0;
    padding: 10px;
    margin-bottom: 10px;
    font-size: 16px;
}

.submit-button {
    margin: 20px 15px;
}

.admin-list-container {
    margin: 15px;
    background: white;
    border-radius: 10px;
    padding: 10px 0;
}

.section-title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    padding: 10px 15px;
    border-bottom: 1px solid #f0f0f0;
}

.button-group {
    display: flex;
    width: 25vw;
    justify-content: space-around;
}
</style>